package com.robot.tools.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.io.File;

/**
 * @author wuyunbin
 */
@Service
public class OssService {
    @Autowired
    private IdWorker idWorker;

    @Value("${aliyun.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.ossPath}")
    private String ossPath;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucket}")
    private String bucket;

    private final Logger logger= LoggerFactory.getLogger(this.getClass());

    /**
     * 上传文件
     *
     * @param src
     * @return
     */
    public String upload(String src) {
        logger.info("src="+src);
        String suffixName = checkImage(src);
        if ("".equals(suffixName)) {
            return "";
        }

        return fileUploader(idWorker.nextId() + "" + suffixName, src);
    }

    private String fileUploader(String objectName, String filePath) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, objectName, new File(filePath));

        //上传文件
        ossClient.putObject(putObjectRequest);

        // 关闭OSSClient。
        ossClient.shutdown();

        //返回oss存储路径
        return objectName;
    }

    /**
     * 检查是否是图片
     *
     * @param src
     * @return
     */
    private String checkImage(String src) {
        logger.info("src="+src);
        String point = ".";
        int flag = 0;
        if (!src.contains(point)) {
            return "";
        }
        String suffixName = src.substring(src.lastIndexOf("."));
        String[] formatImage = {".jpg", ".jpeg", ".bmp", ".png"};
        for (String f : formatImage) {
            if (f.equals(suffixName)) {
                flag++;
            }
        }
        if (flag == 0) {
            logger.info("not a picture");
            return "";
        }
        return suffixName;
    }
}
